package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionBehaviorService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApuserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private ApCollectionMapper apCollectionMapper;

    /**
     * 收藏功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult ApCollectionBehavior(CollectionBehaviorDto dto) {
        //1.参数检查
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.从线程中去获取用户信息   获取当前用户登录的id
        ApUser apUser = ApuserThreadLocalUtil.get();
        if (apUser ==null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.获取用户的id
        Integer apUserId = null;
        if (apUser != null){
            apUserId = apUser.getId();
            if (apUserId == 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
        }

        //4.将数据存储到redis中
        //定义一个唯一的key
        String key = "COLLECTION_" + apUserId;

        Map<String, String> map = new HashMap<>();
        map.put("entryId",dto.getEntryId() + "");
        map.put("type",dto.getType()+"");
        map.put("operation",dto.getOperation() + "");
        map.put("publishTime","2022");

        cacheService.hPut(key,dto.getEntryId() + "", JSON.toJSONString(map));
        //cacheService.hPutAll(key,map);

        //5.保存到数据库中
        if (dto.getOperation() == 0){
            //保存到收藏表里面
            ApCollection apCollection = new ApCollection();
            apCollection.setEntryId(1);
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishTime());
            apCollection.setType(dto.getType());

            apCollectionMapper.insert(apCollection);
        }else {
            apCollectionMapper.delete(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId,dto.getEntryId()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
